<?php

class Document extends FMIS_Controller 
{

	public function __construct() {
		parent::__construct();
        $this->load->model('File_model');
	}

    private $mime_desc = array(
        'documents' => array(
            'application/powerpoint' => "PowerPoint Presentation",
            'application/vnd.ms-powerpoint' => "PowerPoint Presentation",
            'application/vnd.openxmlformats-officedocument.presentationml.presentation' => "PowerPoint Presentation",
            'application/excel' => "Excel Spreadsheet",
            'application/vnd.ms-excel' => "Excel Spreadsheet",
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => "Excel Spreadsheet",
            'application/msexcel' => "Excel Spreadsheet",
            'application/pdf' => "Portable Document Format",
            'application/msword' => "Word Document",
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => "Word Document",
            'text/html' => "HyperText Markup Language File",
            'text/latex' => "TeX File",
            'text/rtf' => "Rich Text File",
            'text/plain' => "Text File"
        ),
        'images' => array(
            'jpeg' => "JPEG Image"
            // TODO add more in these...
        )
    );
    private $uploads_dir = './uploads';

    public function view()
    {
    	$this->load->database();
        $filter = $this->input->post('filter');
        if($filter == 0)
        {
            $this->setup_view('document/view',
                array(
                    'page_title' => "Documents",
                    'message' => '',
                    //'uploads' => get_filenames("{$this->uploads_dir}/documents", TRUE),
                    'uploads' => $this->getFileInfos(),
                    'mime_desc' => $this->mime_desc['documents']
                )
            );
        }
        else
        {
            $filterText = $this->input->post('input-search')."%";
            $filterText = str_replace(" ", "_", $filterText);
            $this->setup_view('document/view', array(
                'page_title' => "Documents",
                'message' => '',
                'uploads' => $this->getFileInfos($filter, $filterText),
                'mime_desc' => $this->mime_desc['documents'],
                'mode' => $filter
            ));
        }
    }


    public function upload($type)
    {
        $config['upload_path'] = './uploads/documents/'.$this->session->userdata('user_id');
        $config['allowed_types'] = 'doc|docx|xls|xlsx|pdf|ppt|pptx|word|tex|latex|htm|html|rtf|txt';
        $config['file_name'] = $this->input->post('file_name');
        $config['overwrite'] = true;

        if (!file_exists($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }

        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        $this->load->library('user_agent');

        if( ! ($this->upload->do_upload($type))) {
            $data = array(
                'page_title' => 'Error',
                'message' => $this->upload->display_errors(),
                'referrer' => $this->agent->referrer()
            );
        }
        else {
            $data = array(
                'page_title' => 'Success',
                'message' => 'Your file has been successfully uploaded',
                'referrer' => $this->agent->referrer()
            );
            $file_info = get_file_info($config['upload_path']."/".$config['file_name'], array('size'));
            //file upload metadata
            $file_metadata = array(
                'name' => $this->input->post('file_name'),
                //'name' => $fileName,
                'ownerID' => $this->session->userdata('user_id'),
                'path' => $config['upload_path'],
                'date' => date('Y-m-d H:i:s'),
                'type' => 1,
                'size' => $file_info['size']
            );
            $this->load->model('File_model');
            $this->File_model->uploadFile($file_metadata);
        }
        $this->setup_view('upload_details', $data);
    }


    public function download($parent, $name)
    {
        //$name = str_replace("%20", " ", $name);
        $this->load->helper('download');
        $data = file_get_contents("./uploads/documents/".$parent."/".$name);
        force_download($name, $data);
    }

    public function remove($fileId, $parent, $name)
    {
        //$name = str_replace("%20", " ", $name);
        $this->load->helper('file');
        $this->load->library('user_agent');

        unlink("./uploads/documents/".$parent."/".$name);
        //$this->view();
        $data = array(
            'page_title' => 'Success',
            'message' => 'Your file has been successfully removed',
            'referrer' => $this->agent->referrer()
        );
        $this->File_model->archiveFile($fileId);
        $this->setup_view('upload_details', $data);
        //delete_files("./uploads/documents/".$parent."/".$name);
    }

    public function search()
    {
        $this->setup_view('test', array(
           'search' => $this->input->post('input-search'),
            'filter' => $this->input->post('filter')
        ));
    }

    private function to_file_size($bytes)
    {
        $sizes = array(
            'P' => pow(2, 50),
            'T' => pow(2, 40),
            'G' => pow(2, 30),
            'M' => pow(2, 20),
            'k' => pow(2, 10)
        );
        foreach($sizes as $prefix => $size)
            if($bytes / $size >= 1)
                return ceil($bytes / $size) . " {$prefix}B";
        return "$bytes bytes";
    }

    private function getFileInfos($mode = 0, $filterText = "")
    {
        $this->load->model('File_model');
        $fileInfos = array();
        //$uploads = get_filenames("{$this->uploads_dir}/documents", TRUE);
        //TODO: make this dependent to the database, not in the file system
        $uploads = $this->File_model->getFiles($mode, $filterText);
        foreach($uploads as $upload)
        {
            /*$upload_info = get_file_info("$upload", array(
                'server_path', 'name', 'size', 'date'
            ));*/
            //$parent = basename(dirname($upload_info['server_path']));
            $parent = $upload['MemberID'];
            //$row = $this->Faculty_Profile_Model->getById($parent);
            //$owner = $row['FirstName']." ".$row['LastName'];
            $owner = $upload['Owner'];
            $mime = get_mime_by_extension($upload['Filename']);

            /*$file_info = array(
                'from_getFileNames' => $upload,
                'name' => $upload_info['name'],
                'server_path' => $upload_info['server_path'],
                'size' => $this->to_file_size($upload_info['size']),
                'date' => $upload_info['date'],
                'owner' => $owner,
                'mime' => $mime,
                'id' => $parent
            );*/

            $file_info = array(
              'name' => $upload['Filename'],
              'size' => $upload['Size'],
              'date' => $upload['Date'],
               'owner' =>$owner,
                'mime' =>$this->mime_desc['documents'][$mime],
                'id' => $parent,
                'path' => $upload['Path'],
                'fileId' => $upload['FileId']
            );
            array_push($fileInfos, $file_info);
        }
        return $fileInfos;
    }
}

/* End of file pages.php */
/* Location: ./application/controllers/pages.php */